/**
 * 
 * @param options       showToastAndRedirect({
        title: "登录成功",
        icon: "success",
        duration: 1500,
        redirect: () => {
          uni.navigateBack(); // 或 uni.switchTab / uni.redirectTo 等
        }
      });
 */
export const showToastAndRedirect = (options: {
  title: string
  icon?: 'success' | 'loading' | 'error' | 'none' | 'fail' | 'exception'
  duration?: number
  redirect?: () => void
}) => {
  const { title, icon = 'success', duration = 1500, redirect } = options

  uni.showToast({
    title,
    icon,
    duration,
  })

  setTimeout(() => {
    if (typeof redirect === 'function') {
      redirect()
    } else {
      uni.navigateBack()
    }
  }, duration)
}

export const formatDate = (timestamp: any) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0')

  // const hours = String(date.getHours()).padStart(2, '0')
  // const minutes = String(date.getMinutes()).padStart(2, '0')
  // const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day}`
  // return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
export const getRandomElements = (arr: any, num: any) => {
  // 克隆原数组，避免修改原始数据
  const shuffled = [...arr]
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
  }
  return shuffled.slice(0, num)
}

// 格式化时长
export const formatDuration = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`.split('.').shift()
}

// 格式化观看次数
export const formatViews = (views?: number) => {
  if (!views) return '0'
  if (views < 1000) return `${views}`
  if (views < 10000) return `${(views / 1000).toFixed(1)}千`
  return `${(views / 10000).toFixed(1)}万`
}

export const formatTimestampStartAndEnd = (startTimestamp: string, endTimestamp: string) => {
  function formatTimestamp(timestamp: string, bol: boolean) {
    const date = new Date(timestamp)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return bol
      ? `${year}年${month}月${day}日 ${hours}:${minutes}`
      : `${month}月${day}日 ${hours}:${minutes}`
  }
  const startDate = formatTimestamp(startTimestamp, true)
  const endDate = formatTimestamp(endTimestamp, false)
  return `${startDate} - ${endDate}`
}
